package com.imti.mall.order.controller;

import com.imti.mall.common.Api.CommonResult;
import com.imti.mall.model.order.pojo.OmsOrderSetting;
import com.imti.mall.order.service.OrderSettingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Timer;
import java.util.TimerTask;

@RestController
@Api(tags = "订单设置管理")
@RequestMapping("/api/v1/orderSetting")
public class OrderSettingController {
    @Autowired
    OrderSettingService orderSettingService;


    @ApiOperation(value = "获取设置")
    @GetMapping(value="/getSetting")
    public CommonResult<OmsOrderSetting> getSetting(){
        OmsOrderSetting omsOrderSetting= orderSettingService.getSetting();
        return CommonResult.success(omsOrderSetting);
    }



    @ApiOperation(value = "订单设置")
    @PostMapping(value="/setting")
    public CommonResult setting(OmsOrderSetting omsOrderSetting){
        int result=orderSettingService.addOrderSetting(omsOrderSetting);
        TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                int[] ids=orderSettingService.findFlashNotPayId();//查询秒杀订单未付款的id
                for(int i=0;i<ids.length;i++){
                  orderSettingService.closeFlashOrder(ids[i]);//关闭超时的秒杀订单
                  orderSettingService.setFlashNotPayHistory(ids[i]);//将关闭的操作写入操作表
                }

                int[] id2=orderSettingService.findNomalNotPayId();
                for(int j=0;j<id2.length;j++){
                    orderSettingService.closeNormalOrder(id2[j]);
                    orderSettingService.setNormalNotPayHistory(id2[j]);
                }

                int[] id3=orderSettingService.findNotGet();
                for(int k=0;k<id3.length;k++){
                    orderSettingService.finishOrder(id3[k]);
                    orderSettingService.setHistoryNotGet(id3[k]);
                }

            }
        };
        Timer timer=new Timer();
        timer.schedule(timerTask,1000,300000);//延迟一秒，五分种刷新一次
        return CommonResult.success(true);
    }
}
